import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path/path.dart' as path;

import '../AI/tina_dart/BaseAPI.dart';
import '../AI/dify_datasets.dart';
import '../serve/file_serve.dart';

class SettingPage extends StatefulWidget {
  final BaseAPI llm;
  final DifyKnowledgeDatabase difyKnowledge;
  final String appDataDir;
  final FileServe? fileServe;

  const SettingPage({
    Key? key,
    required this.llm,
    required this.difyKnowledge,
    required this.appDataDir,
    this.fileServe,
  }) : super(key: key);

  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> with TickerProviderStateMixin {
  late TextEditingController _llmBaseUrlController;
  late TextEditingController _llmApiKeyController;
  late TextEditingController _llmModelController;
  late TextEditingController _difyBaseUrlController;
  late TextEditingController _difyApiKeyController;
  late TextEditingController _ocrAppIdController;
  late TextEditingController _ocrSecretKeyController;
  late TextEditingController _ocrApiUrlController;
  bool _isLoading = true;
  bool _isEditing = false;
  Map<String, dynamic> _llmConfig = {};
  Map<String, dynamic> _difyConfig = {};
  Map<String, dynamic> _ocrConfig = {};
  
  late AnimationController _animationController;
  late Animation<double> _fadeAnimation;
  late Animation<Offset> _slideAnimation;

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 1000),
    );
    _fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOut),
    );
    _slideAnimation = Tween<Offset>(begin: Offset(0, 0.3), end: Offset.zero).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOut),
    );
    _loadConfigs();
  }

  Future<void> _loadConfigs() async {
    try {
      // 加载LLM配置
      final llmConfigPath = path.join(widget.appDataDir, 'config', 'LLM.json');
      final llmFile = File(llmConfigPath);
      final llmContent = await llmFile.readAsString();
      _llmConfig = jsonDecode(llmContent);
      
      // 加载Dify配置
      final difyConfigPath = path.join(widget.appDataDir, 'config', 'dify_dataset.json');
      final difyFile = File(difyConfigPath);
      final difyContent = await difyFile.readAsString();
      _difyConfig = jsonDecode(difyContent);
      
      // 加载OCR配置
      try {
        final ocrConfigPath = path.join(widget.appDataDir, 'config', 'vivo_ocr.json');
        final ocrFile = File(ocrConfigPath);
        if (await ocrFile.exists()) {
          final ocrContent = await ocrFile.readAsString();
          _ocrConfig = jsonDecode(ocrContent);
        } else {
          // 如果OCR配置文件不存在，使用默认值
          _ocrConfig = {
            "app_id": "your_app_id",
            "secret_key": "your_secret_key",
            "api_url": "https://ai-gateway.vivo.com.cn/api/v1/ocr"
          };
        }
      } catch (e) {
        print('加载OCR配置失败，使用默认值: $e');
        _ocrConfig = {
          "app_id": "your_app_id",
          "secret_key": "your_secret_key",
          "api_url": "https://ai-gateway.vivo.com.cn/api/v1/ocr"
        };
      }
      
      // 初始化控制器
      _llmBaseUrlController = TextEditingController(text: _llmConfig['base_url']);
      _llmApiKeyController = TextEditingController(text: _llmConfig['api_key']);
      _llmModelController = TextEditingController(text: _llmConfig['model']);
      _difyBaseUrlController = TextEditingController(text: _difyConfig['dify_base_url']);
      _difyApiKeyController = TextEditingController(text: _difyConfig['dify_dataset_api']);
      _ocrAppIdController = TextEditingController(text: _ocrConfig['app_id']);
      _ocrSecretKeyController = TextEditingController(text: _ocrConfig['secret_key']);
      _ocrApiUrlController = TextEditingController(text: _ocrConfig['api_url']);
      
      setState(() {
        _isLoading = false;
      });
      
      // 启动动画
      _animationController.forward();
    } catch (e) {
      print('加载配置失败: $e');
      setState(() {
        _isLoading = false;
      });
      _animationController.forward();
    }
  }

  @override
  void dispose() {
    _llmBaseUrlController.dispose();
    _llmApiKeyController.dispose();
    _llmModelController.dispose();
    _difyBaseUrlController.dispose();
    _difyApiKeyController.dispose();
    _ocrAppIdController.dispose();
    _ocrSecretKeyController.dispose();
    _ocrApiUrlController.dispose();
    _animationController.dispose();
    super.dispose();
  }

  Future<void> _saveConfigs() async {
    try {
      // 更新LLM配置
      _llmConfig['base_url'] = _llmBaseUrlController.text;
      _llmConfig['api_key'] = _llmApiKeyController.text;
      _llmConfig['model'] = _llmModelController.text;
      
      // 更新Dify配置
      _difyConfig['dify_base_url'] = _difyBaseUrlController.text;
      _difyConfig['dify_dataset_api'] = _difyApiKeyController.text;
      
      // 更新OCR配置
      _ocrConfig['app_id'] = _ocrAppIdController.text;
      _ocrConfig['secret_key'] = _ocrSecretKeyController.text;
      _ocrConfig['api_url'] = _ocrApiUrlController.text;
      
      // 保存LLM配置
      final llmConfigPath = path.join(widget.appDataDir, 'config', 'LLM.json');
      final llmFile = File(llmConfigPath);
      await llmFile.writeAsString(jsonEncode(_llmConfig));
      
      // 保存Dify配置
      final difyConfigPath = path.join(widget.appDataDir, 'config', 'dify_dataset.json');
      final difyFile = File(difyConfigPath);
      await difyFile.writeAsString(jsonEncode(_difyConfig));
      
      // 保存OCR配置
      final ocrConfigPath = path.join(widget.appDataDir, 'config', 'vivo_ocr.json');
      final ocrFile = File(ocrConfigPath);
      await ocrFile.writeAsString(jsonEncode(_ocrConfig));
      
      // 如果提供了fileServe，使用它的updateOCRConfig方法更新OCR配置
      if (widget.fileServe != null) {
        await widget.fileServe!.updateOCRConfig(_ocrConfig);
      }
      
      setState(() {
        _isEditing = false;
      });
      
      _showSuccessMessage('设置已保存，请重启应用以应用更改');
    } catch (e) {
      _showErrorMessage('保存配置失败: $e');
    }
  }

  void _showSuccessMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.green[400],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        margin: EdgeInsets.all(16),
      ),
    );
  }

  void _showErrorMessage(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: Colors.red[400],
        behavior: SnackBarBehavior.floating,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
        margin: EdgeInsets.all(16),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      body: _isLoading 
          ? _buildLoadingScreen()
          : _buildSettingScreen(),
    );
  }

  Widget _buildLoadingScreen() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
        ),
      ),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 80,
              height: 80,
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                strokeWidth: 3,
              ),
            ),
            SizedBox(height: 24),
            Text(
              '加载设置信息...',
              style: TextStyle(
                color: Colors.white,
                fontSize: 18,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSettingScreen() {
    return CustomScrollView(
      slivers: [
        // 美化的顶部区域
        SliverToBoxAdapter(
          child: _buildBeautifulHeader(),
        ),
        // 设置内容区域
        SliverToBoxAdapter(
          child: _isEditing ? _buildEditForm() : _buildSettingsView(),
        ),
      ],
    );
  }

  Widget _buildBeautifulHeader() {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
          colors: [
            Color(0xFF667eea),
            Color(0xFF764ba2),
          ],
        ),
        borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(32),
          bottomRight: Radius.circular(32),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: SafeArea(
        child: FadeTransition(
          opacity: _fadeAnimation,
          child: SlideTransition(
            position: _slideAnimation,
            child: Padding(
              padding: EdgeInsets.fromLTRB(24, 20, 24, 40),
              child: Column(
                children: [
                  // 头部标题
                  Row(
                    children: [
                      // 返回按钮
                      Container(
                        decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.2),
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: IconButton(
                          icon: Icon(Icons.arrow_back, color: Colors.white),
                          onPressed: () => Navigator.pop(context),
                        ),
                      ),
                      SizedBox(width: 12),
                      Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
                              '应用设置',
                              style: TextStyle(
                                fontSize: 28,
                                fontWeight: FontWeight.w800,
                                color: Colors.white,
                                letterSpacing: 0.5,
                              ),
                            ),
                            Text(
                              '配置大模型、知识库和OCR服务',
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.white.withOpacity(0.8),
                                fontWeight: FontWeight.w500,
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 编辑按钮
                      if (!_isEditing)
                        Container(
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: IconButton(
                            icon: Icon(Icons.edit, color: Colors.white),
                            onPressed: () {
                              setState(() {
                                _isEditing = true;
                              });
                            },
                          ),
                        ),
                    ],
                  ),
                  
                  SizedBox(height: 32),
                  
                  // 状态指示器
                  Row(
                    children: [
                      _buildStatusIndicator(
                        '大模型',
                        _llmConfig['api_key']?.isNotEmpty ?? false,
                        Icons.psychology,
                      ),
                      SizedBox(width: 16),
                      _buildStatusIndicator(
                        '知识库',
                        _difyConfig['dify_dataset_api']?.isNotEmpty ?? false,
                        Icons.library_books,
                      ),
                      SizedBox(width: 16),
                      _buildStatusIndicator(
                        'OCR',
                        _ocrConfig['app_id']?.isNotEmpty ?? false,
                        Icons.camera_alt,
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildStatusIndicator(String label, bool isConfigured, IconData icon) {
    return Expanded(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 12),
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.15),
          borderRadius: BorderRadius.circular(16),
          border: Border.all(color: Colors.white.withOpacity(0.2)),
        ),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.all(8),
              decoration: BoxDecoration(
                color: isConfigured 
                    ? Colors.green.withOpacity(0.3)
                    : Colors.orange.withOpacity(0.3),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                icon,
                color: Colors.white,
                size: 20,
              ),
            ),
            SizedBox(height: 8),
            Text(
              label,
              style: TextStyle(
                color: Colors.white,
                fontSize: 12,
                fontWeight: FontWeight.w600,
              ),
            ),
            SizedBox(height: 4),
            Container(
              width: 8,
              height: 8,
              decoration: BoxDecoration(
                color: isConfigured ? Colors.green : Colors.orange,
                shape: BoxShape.circle,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSettingsView() {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: Container(
        margin: EdgeInsets.all(24),
        child: Column(
          children: [
            _buildSettingsSection(
              '🧠 大模型设置',
              [
          _buildSettingCard(
            title: '模型',
                  value: _llmConfig['model'] ?? '未设置',
            icon: Icons.science,
          ),
          _buildSettingCard(
            title: 'API 地址',
                  value: _llmConfig['base_url'] ?? '未设置',
            icon: Icons.link,
          ),
          _buildSettingCard(
            title: 'API 密钥',
            value: _maskApiKey(_llmConfig['api_key'] ?? ''),
            icon: Icons.key,
          ),
              ],
            ),
            
            SizedBox(height: 20),
            
            _buildSettingsSection(
              '📚 知识库设置',
              [
          _buildSettingCard(
            title: 'Dify API 地址',
                  value: _difyConfig['dify_base_url'] ?? '未设置',
            icon: Icons.link,
          ),
          _buildSettingCard(
            title: 'Dify API 密钥',
            value: _maskApiKey(_difyConfig['dify_dataset_api'] ?? ''),
            icon: Icons.key,
          ),
          _buildSettingCard(
            title: '数据集 ID',
            value: _difyConfig['dataset_id'] ?? '未创建',
            icon: Icons.dataset,
          ),
              ],
            ),
            
            SizedBox(height: 20),
            
            _buildSettingsSection(
              '👁️ OCR设置',
              [
          _buildSettingCard(
            title: 'VIVO OCR App ID',
            value: _maskApiKey(_ocrConfig['app_id'] ?? ''),
            icon: Icons.app_registration,
          ),
          _buildSettingCard(
            title: 'VIVO OCR Secret Key',
            value: _maskApiKey(_ocrConfig['secret_key'] ?? ''),
            icon: Icons.key,
          ),
          _buildSettingCard(
            title: 'VIVO OCR API 地址',
                  value: _ocrConfig['api_url'] ?? '未设置',
            icon: Icons.link,
          ),
              ],
            ),
            
            SizedBox(height: 20),
            
            _buildSettingsSection(
              '🗂️ 其他设置',
              [
          _buildSettingCard(
            title: '应用数据目录',
            value: widget.appDataDir,
            icon: Icons.folder,
          ),
        ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSettingsSection(String title, List<Widget> cards) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(24),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.08),
            blurRadius: 20,
            offset: Offset(0, 10),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(20),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
              ),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(24),
                topRight: Radius.circular(24),
              ),
            ),
            child: Text(
              title,
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.w700,
                color: Colors.grey[800],
              ),
            ),
          ),
          ...cards,
        ],
      ),
    );
  }

  Widget _buildEditForm() {
    return FadeTransition(
      opacity: _fadeAnimation,
      child: Container(
        margin: EdgeInsets.all(24),
        padding: EdgeInsets.all(28),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(32),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.08),
              blurRadius: 30,
              offset: Offset(0, 20),
            ),
          ],
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 表单标题
            Row(
              children: [
                Container(
                  padding: EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    gradient: LinearGradient(
                      colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                    ),
                    borderRadius: BorderRadius.circular(12),
                  ),
                  child: Icon(
                    Icons.edit,
                    color: Colors.white,
                    size: 20,
                  ),
                ),
                SizedBox(width: 12),
                Text(
                  '编辑设置',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.w700,
                    color: Colors.grey[800],
                  ),
                ),
              ],
            ),
            
            SizedBox(height: 32),
            
            _buildFormSection('🧠 大模型设置', [
          _buildTextField(
            label: '模型',
            controller: _llmModelController,
            hint: '输入模型名称，如 qwen-plus',
                icon: Icons.science,
          ),
          _buildTextField(
            label: 'API 地址',
            controller: _llmBaseUrlController,
            hint: '输入API地址',
                icon: Icons.link,
          ),
          _buildTextField(
            label: 'API 密钥',
            controller: _llmApiKeyController,
            hint: '输入API密钥',
                icon: Icons.key,
            isPassword: true,
          ),
            ]),
            
          SizedBox(height: 24),
            
            _buildFormSection('📚 知识库设置', [
          _buildTextField(
            label: 'Dify API 地址',
            controller: _difyBaseUrlController,
            hint: '输入Dify API地址',
                icon: Icons.link,
          ),
          _buildTextField(
            label: 'Dify API 密钥',
            controller: _difyApiKeyController,
            hint: '输入Dify API密钥',
                icon: Icons.key,
                isPassword: true,
          ),
            ]),
            
          SizedBox(height: 24),
            
            _buildFormSection('👁️ OCR设置', [
          _buildTextField(
            label: 'VIVO OCR App ID',
            controller: _ocrAppIdController,
            hint: '输入VIVO OCR App ID',
                icon: Icons.app_registration,
          ),
          _buildTextField(
            label: 'VIVO OCR Secret Key',
            controller: _ocrSecretKeyController,
            hint: '输入VIVO OCR Secret Key',
                icon: Icons.key,
                isPassword: true,
          ),
          _buildTextField(
            label: 'VIVO OCR API 地址',
            controller: _ocrApiUrlController,
            hint: '输入VIVO OCR API地址',
                icon: Icons.link,
              ),
            ]),
            
            SizedBox(height: 40),
            
            // 按钮组
            Row(
            children: [
                Expanded(
                  child: Container(
                    height: 56,
                    decoration: BoxDecoration(
                      color: Colors.grey[100],
                      borderRadius: BorderRadius.circular(16),
                    ),
                    child: TextButton(
                onPressed: () {
                  setState(() {
                    _isEditing = false;
                  });
                },
                      style: TextButton.styleFrom(
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16),
                        ),
                      ),
                      child: Text(
                        '取消',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                          color: Colors.grey[600],
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(width: 16),
                Expanded(
                  flex: 2,
                  child: Container(
                    height: 56,
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                      ),
                      borderRadius: BorderRadius.circular(16),
                      boxShadow: [
                        BoxShadow(
                          color: Color(0xFF667eea).withOpacity(0.3),
                          blurRadius: 20,
                          offset: Offset(0, 10),
                        ),
                      ],
                    ),
                    child: ElevatedButton(
                      onPressed: _saveConfigs,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.transparent,
                        foregroundColor: Colors.white,
                        elevation: 0,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(16),
                        ),
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.save, size: 20),
              SizedBox(width: 8),
                          Text(
                            '保存设置',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
              ),
            ],
          ),
        ],
      ),
      ),
    );
  }

  Widget _buildFormSection(String title, List<Widget> fields) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: 18,
            fontWeight: FontWeight.w700,
            color: Colors.grey[700],
          ),
        ),
        SizedBox(height: 16),
        ...fields,
      ],
    );
  }

  Widget _buildSettingCard({
    required String title,
    required String value,
    required IconData icon,
  }) {
    return Container(
      margin: EdgeInsets.only(bottom: 2),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(color: Colors.grey[100]!, width: 1),
        ),
      ),
      child: Padding(
        padding: EdgeInsets.symmetric(horizontal: 20, vertical: 16),
        child: Row(
          children: [
            Container(
              padding: EdgeInsets.all(8),
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [Color(0xFF667eea).withOpacity(0.1), Color(0xFF764ba2).withOpacity(0.1)],
                ),
                borderRadius: BorderRadius.circular(12),
              ),
              child: Icon(
                icon,
                color: Color(0xFF667eea),
                size: 20,
              ),
            ),
            SizedBox(width: 16),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    title,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w600,
                      color: Colors.grey[800],
                    ),
                  ),
                  SizedBox(height: 4),
                  Text(
          value,
                    style: TextStyle(
                      fontSize: 14,
                      color: Colors.grey[600],
                      fontWeight: FontWeight.w500,
                    ),
          overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildTextField({
    required String label,
    required TextEditingController controller,
    required String hint,
    required IconData icon,
    bool isPassword = false,
  }) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                padding: EdgeInsets.all(6),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [Color(0xFF667eea), Color(0xFF764ba2)],
                  ),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(icon, color: Colors.white, size: 16),
              ),
              SizedBox(width: 8),
              Text(
                label,
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey[700],
                ),
              ),
            ],
          ),
          SizedBox(height: 12),
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFFF8F9FA), Color(0xFFE9ECEF)],
              ),
              borderRadius: BorderRadius.circular(16),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 8,
                  offset: Offset(0, 4),
                ),
              ],
            ),
            child: TextField(
            controller: controller,
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
            decoration: InputDecoration(
              hintText: hint,
                hintStyle: TextStyle(color: Colors.grey[500]),
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(16),
                  borderSide: BorderSide.none,
                ),
                contentPadding: EdgeInsets.symmetric(horizontal: 20, vertical: 16),
                filled: true,
                fillColor: Colors.transparent,
              ),
              obscureText: isPassword,
            ),
          ),
        ],
      ),
    );
  }

  String _maskApiKey(String apiKey) {
    if (apiKey.isEmpty) return '未设置';
    if (apiKey.length <= 8) return '*' * apiKey.length;
    return apiKey.substring(0, 4) + '*' * (apiKey.length - 8) + apiKey.substring(apiKey.length - 4);
  }
} 